package com.hongxun.design.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.activitys.BaseActivity;
import com.hongxun.design.adapters.SettingAdapter;
import com.hongxun.design.jungong.model.MaterialDetail;
import com.hongxun.design.jungong.model.MatreialDetailSys;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.utils.RecyclerViewUtils;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.lidroid.xutils.http.RequestParams;
import com.pop.android.common.util.ToastUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class SettingTypeActivity extends BaseActivity {

    RecyclerView recyclerView;
    SettingAdapter adapter;
    ArrayList<MaterialDetail> list = new ArrayList<>();
    ArrayList<String> typeList = new ArrayList<>();
    boolean isUpdate = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting_type);
        isUpdate = getIntent().getBooleanExtra("update", false);
        if (!isUpdate) {
            list = getIntent().getParcelableArrayListExtra("result");
            if (list != null) {
                for (MaterialDetail materialDetail : list) {
                    if (!typeList.contains(materialDetail.getType())) {
                        typeList.add(materialDetail.getType());
                    }
                }
            }
            saveMaterialType();
        } else getListAll();
        initheader();
        findView();

    }

    private void saveMaterialType() {
//        String key = MString.nxMaterialType + MyApp.currProject.getProject_id();
//        ShardPreferencesTool.save(getApplicationContext(), key, FastJsonUtil.beanToJson(typeList), 3);
    }

    private void initheader() {
        TextView centerTitle = (TextView) findViewById(R.id.center_title);
        centerTitle.setText("分类排序");
        findViewById(R.id.back_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putStringArrayListExtra("result", typeList);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });
        Button rightButton = (Button) findViewById(R.id.right_btn);
        if (isUpdate) {
            rightButton.setVisibility(View.VISIBLE);
            rightButton.setText("修改");
            rightButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    update();
                }
            });
        }
    }

    @Override
    protected void findView() {
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(this));
        adapter = new SettingAdapter(typeList);
        recyclerView.setAdapter(adapter);
        ItemTouchHelper.Callback callback = new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                int swipFlag = 0;
                int dragflag = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                return makeMovementFlags(dragflag, swipFlag);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                adapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
                Collections.swap(typeList, viewHolder.getAdapterPosition(), target.getAdapterPosition());
                return true;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            }

            @Override
            public boolean canDropOver(RecyclerView recyclerView, RecyclerView.ViewHolder current, RecyclerView.ViewHolder target) {
                return true;
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return true;
            }
        };

        //1.创建item helper
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
        //2.绑定到recyclerview上面去
        itemTouchHelper.attachToRecyclerView(recyclerView);
        //3.在ItemHelper的接口回调中过滤开启长按拖动，拓展其他操作
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putStringArrayListExtra("result", typeList);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    void update() {
        for (MaterialDetail materialDetail : list) {
            if (typeList.contains(materialDetail.getType())) {
                materialDetail.setSort(typeList.indexOf(materialDetail.getType()));
            }
        }
        final String projectName = MyApp.currProject.getProject_name();
        if (projectName.isEmpty()) {
            ToastUtils.showToast(this, "请先选择项目!");
            return;
        }
        showWaitDialog(-1, "处理中...");
        RequestParams params = new RequestParams();
        params.addBodyParameter("pro_id", MyApp.currProject.getStage_id());
        params.addBodyParameter("pro_name", projectName);
        String jsonString = JSON.toJSONString(list);
        params.addBodyParameter("material_all", jsonString);
        MyApp.HTTP.updateSort(handler, params);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HttpStringUtil.SUCCESSED:
                    hideWaitIngDialog();
                    String valueOf = String.valueOf(msg.obj);
                    //正确的时候(不含code，msg)
                    if (FastJsonUtil.JsonToCheck(valueOf)) {
                        if (valueOf.contains(":")) {
                            String ver_ID = valueOf.substring(valueOf.lastIndexOf(":") + 1, valueOf.length() - 1).trim();
                            MyApp.currProject.setCodeset_version_id(ver_ID);
                        }
                        ToastUtils.showToast(SettingTypeActivity.this, "排序设置成功");
                        getListAll();
                    } else {
                        ToastUtils.showToast(SettingTypeActivity.this, FastJsonUtil.JsonToCheck_String(String.valueOf(msg.obj)));
                    }
                    break;
                case 2:
                    hideWaitIngDialog();
                    if (null != msg.obj) jsonToData(String.valueOf(msg.obj));
                    break;
            }
        }
    };

    void getListAll() {
        String name = MyApp.currProject.getProject_name().trim();
        if (name.isEmpty()) return;
        String versionId = MyApp.currProject.getCodeset_version_id().trim();
        if (versionId.isEmpty()) {
            ToastUtils.showToast(this, "请先手动上传项目材料");
            return;
        }
        showWaitDialog(-1, "数据获取中...");
        MyApp.HTTP.getMaterialListAll(handler, 2, "", "", versionId);
    }

    private void jsonToData(String json) {
        if (list != null) list.clear();
        else list = new ArrayList<>();
        List<MatreialDetailSys> toGetT = FastJsonUtil.getMaterialList(json);
        if (toGetT != null)
            for (MatreialDetailSys detailSys : toGetT) {
                MaterialDetail detail = new MaterialDetail();
                detail.setNum(String.valueOf(detailSys.getNum()));
                detail.setUnit(String.valueOf(detailSys.getUnit()));
                detail.setSpec(String.valueOf(detailSys.getSpec()));
                detail.setMaterial_number(String.valueOf(detailSys.getMaterial_number()));
                detail.setName(String.valueOf(detailSys.getName()));
                detail.setType(String.valueOf(detailSys.getType()));
                detail.setSort(detailSys.getSort());
                list.add(detail);
            }

        if (typeList != null) typeList.clear();
        else typeList = new ArrayList<>();

        for (MaterialDetail materialDetail : list) {
            if (!typeList.contains(materialDetail.getType())) {
                typeList.add(materialDetail.getType());
            }
        }
        saveMaterialType();
        adapter.notifyDataSetChanged();
    }
}
